﻿using System;
using System.Windows.Forms;
using Devv.Core.Erroo;
using Yglu.BusinessLayer.Entities;

namespace Yglu.TerminalApp
{
	public partial class ChangeUserForm : Form
	{
		#region Main methods

		public ChangeUserForm()
		{
			InitializeComponent();
		}

		private void ChangeUserForm_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				Login();
			}
			else if (e.KeyCode == Keys.Escape)
			{
				if (Program.LoggedUser == null)
				{
					Application.Exit();
				}
				else
				{
					Close();
				}
			}
		}

		private void ChangeUserForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (Program.LoggedUser == null)
			{
				Application.Exit();
			}
		}

		#endregion

		#region Login

		private void imgAccept_Click(object sender, EventArgs e)
		{
			Login();
		}

		private void Login()
		{
			if (txtID.Text.Length < 1 || txtPassword.Text.Length < 5)
			{
				return;
			}

			Int32 id;
			String password;

			try
			{
				id = Convert.ToInt32(txtID.Text);
				password = txtPassword.Text;

				User user = new User(id, password);

				if (user.Id < 1 || !user.Active)
				{
					MessageBox.Show(Messages.UserInvalid, Messages.Login, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				}
				else
				{
					Program.LoggedUser = user;
					Program.MainForm.Show();

					Close();
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.ToString());
				ErrorHandler.Handle(ex);
			}
		}

		#endregion
	}
}